package com.dwd.hrm.service.impl;

import com.alibaba.fastjson.JSON;
import com.dwd.hrm.domain.LoginUser;
import com.dwd.hrm.domain.VipUser;
import com.dwd.hrm.mapper.LoginUserMapper;
import com.dwd.hrm.properties.ClientDetailsAdminProperties;
import com.dwd.hrm.properties.ClientDetailsWebsiteProperties;
import com.dwd.hrm.service.ILoginUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dwd.hrm.util.AjaxResult;
import com.dwd.hrm.util.HttpUtil;
import com.dwd.hrm.utils.ValidUtils;
import com.dwd.hrm.vo.AccessTokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wendi
 * @since 2021-03-05
 */
@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {
    @Autowired
    private LoginUserMapper loginUserMapper;
    @Value("${auth.password.tokenurl}")
    private String tokenUrl;

    @Autowired
    private ClientDetailsAdminProperties clientDetailsAdminProperties;
    @Autowired
    private ClientDetailsWebsiteProperties clientDetailsWebsiteProperties;

    @Override
    public boolean insert(LoginUser loginUser) {
        //先保存用户信息表login_user  返回主键
        super.insert(loginUser);
        //存中间表user_meal表   login_user_id和meal_id    为了关联meal
        loginUserMapper.addUserMeal(loginUser.getId(), loginUser.getMealId());
        return true;
    }

    @Override
    public AjaxResult login(LoginUser loginUser) {
        //判断参数
        String username = loginUser.getUsername();
        String password = loginUser.getPassword();
        Integer type = loginUser.getType();
        ValidUtils.assertNotNull(username, "用户名不能为空");
        ValidUtils.assertNotNull(password, "密码不能为空");
        ValidUtils.assertNotNull(type, "系统问题");

        String clientId = null;
        String secret = null;
        //拼接
        if (loginUser.getType().intValue() == LoginUser.ADMIN) {
            clientId = clientDetailsAdminProperties.getClientId();
            secret = clientDetailsAdminProperties.getSecret();
        } else {
            clientId = clientDetailsWebsiteProperties.getClientId();
            secret = clientDetailsWebsiteProperties.getSecret();
        }
        //获取url
        String url = String.format(tokenUrl, clientId, secret, username, password);
        Map<String, String> map = HttpUtil.sendPost(url);
        //判断token
        String token = map.get("access_token");
        boolean success = true;
        String error_description = null;
        if (token == null) {
            success = false;
            error_description = map.get("error_description");
        }
        return AjaxResult.me().setResultObj(map).setSuccess(success).setMessage(error_description);
    }

    /**
     * 无感刷新
     *
     * @param refreshToken
     * @param type
     * @return
     */
    @Override
    public AccessTokenVo refresh(String refreshToken, Integer type) {
        String URL_TOKEN_REFRESH =
                "http://localhost:5010/oauth/token?client_id=%s&client_secret=%s&grant_type=refresh_token&refresh_token=%s";
        String clientId = null;
        String secret = null;
        if (type.intValue() == LoginUser.ADMIN) {
            clientId = clientDetailsAdminProperties.getClientId();
            secret = clientDetailsAdminProperties.getSecret();
        } else {
            clientId = clientDetailsWebsiteProperties.getClientId();
            secret = clientDetailsWebsiteProperties.getSecret();
        }
        //根据传入的type,得到对应的客户端配置
//        Oauth2ClientDetails clientDetails = clientDetailsWebsiteProperties.getClientDetials(type);

        //1.拼接一个获取oath2的token的url:密码模式
        String url = String.format(URL_TOKEN_REFRESH, clientId, secret, refreshToken);
        //2.发送请求获取token
        Map<String, String> map = HttpUtil.sendPost(url);
        //3.封装结果
        String tokenJson = JSON.toJSONString(map);
        return JSON.parseObject(tokenJson, AccessTokenVo.class);

    }

    @Override
    public LoginUser insert(VipUser vipUser) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(vipUser.getPhone());
        loginUser.setPassword(vipUser.getPassword());
        loginUser.setType(vipUser.getType());
        baseMapper.insert(loginUser);
        System.out.println(loginUser);
        return loginUser;
    }
}
